package com.campusbackend.service.impl;

import com.campusbackend.entity.AdminUsers;
import com.campusbackend.mapper.AdminUsersMapper;
import com.campusbackend.service.AdminUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;

/**
 * <p>
 * 管理员用户表 服务实现类
 * </p>
 *
 * @author yezi
 * @since 2025-07-24
 */
@Slf4j
@Service
public class AdminUsersServiceImpl extends ServiceImpl<AdminUsersMapper, AdminUsers> implements AdminUsersService {

    @Autowired
    private AdminUsersMapper adminUsersMapper;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public AdminUsers findByUsername(String username) {
        return adminUsersMapper.findByUsername(username);
    }

    @Override
    @PostConstruct
    public void initializeAdminPassword() {
        try {
            log.info("开始检查管理员密码初始化...");

            // 查找默认管理员账号
            AdminUsers admin = findByUsername("admin");
            if (admin != null) {
                // 检查密码是否已经是BCrypt格式（BCrypt密码以$2a$开头）
                if (!admin.getPassword().startsWith("$2a$")) {
                    log.info("检测到管理员密码未加密，开始加密处理...");

                    // 假设原始密码是admin123
                    String encodedPassword = passwordEncoder.encode("admin123");
                    admin.setPassword(encodedPassword);

                    // 更新数据库
                    boolean updated = updateById(admin);
                    if (updated) {
                        log.info("管理员密码加密完成");
                    } else {
                        log.error("管理员密码加密失败");
                    }
                } else {
                    log.info("管理员密码已经是加密格式，无需处理");
                }
            } else {
                log.warn("未找到默认管理员账号");
            }
        } catch (Exception e) {
            log.error("管理员密码初始化异常", e);
        }
    }
}
